/**
 * 
 */
package com.fox.webapp.service.impl;

import java.util.List;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fox.webapp.domain.Broker;
import com.fox.webapp.domain.Policy;
import com.fox.webapp.persistent.BrokerRepository;
import com.fox.webapp.persistent.PolicyRepository;
import com.fox.webapp.service.IBrokerService;

/**
 * @author yockii
 *
 */
@Service
public class BrokerService implements IBrokerService {

	private static final Logger logger = LoggerFactory.getLogger(BrokerService.class);
	
	@Autowired
	private BrokerRepository brokerRepository;
	@Autowired
	private PolicyRepository policyRepository;
	
	/* (non-Javadoc)
	 * @see com.fox.webapp.service.IBrokerService#getAllBrokerWithIdAndName()
	 */
	@Override
	public List<Broker> getAllActivedBroker() {
		return brokerRepository.findByActiveIsTrueOrderByOrderAsc();
	}

	@Override
	public Broker addNewBroker(Broker broker) {
		return brokerRepository.save(broker);
	}

	@Override
	public boolean updateBroker(Broker broker) {
		if(broker.getId() == null) return false;
		brokerRepository.updateBroker(broker);
		return true;
	}

	@Override
	public boolean deleteBroker(Broker broker) {
		if(broker.getId() == null) return false;
		brokerRepository.delete(broker);
		return true;
	}

	@Override
	public List<Broker> getAllBrokers() {
		return (List<Broker>) brokerRepository.findAll();
	}

	@Override
	public Policy addNewPolicy(Policy policy, String brokerId) {
		Broker b = brokerRepository.findOne(new ObjectId(brokerId));
		if(b != null){
			return policyRepository.save(policy);
		}
		return null;
	}

	@Override
	public List<Policy> getAllPolicy(ObjectId brokerId) {
		Broker broker = brokerRepository.findOne(brokerId);
		return (List<Policy>) policyRepository.findByBroker(broker);
	}

	@Override
	public Policy updatePolicy(Policy policy) {
		if(policy.getId() != null){
			return policyRepository.updatePolicy(policy);
		}
		return null;
	}

	@Override
	public Broker getBroker(String id) {
		if(!StringUtils.hasText(id) || !ObjectId.isValid(id)) return new Broker();
		return brokerRepository.findOne(new ObjectId(id));
	}

}
